<template>
  <div class="tinymce-wrop" v-loading="isOp">

    <el-drawer title="☁ 云库，请在这里复制文件引用~" :visible.sync="drawer" direction="ttb" style="height:2350px;">
      <resources :id="-1"></resources>
    </el-drawer>

    <el-drawer title="🏷 标签管理" :visible.sync="tagW" direction="btt" :before-close="tagClose">
      <tag></tag>
    </el-drawer>

    <div class="row">
      <div class="col-1 mt-15">
        <span style="font-weight:bold">标题：</span>
      </div>
      <div class="col-11 mt-5">
        <el-input style="border-style:solid;border-width:1px;" type="text" placeholder="请输入标题" v-model="title"
          maxlength="50" show-word-limit>
        </el-input>
      </div>
      <!-- <div class="col-2">
        <button class="btn btn-radius bg-info ml-10 text-white mb-10 mt-5 box-shadow" type="text"
          @click="drawer = true">打开云库</button>
      </div> -->

      <div class="col-1 mt-20">
        <span style="font-weight:bold">封面：</span>
      </div>
      <div class="col-9 mt-10">
        <el-input style="border-style:solid;border-width:1px;" type="text" placeholder="请输入图片路径" v-model="background">
        </el-input>
      </div>
      <div class="col-2 mt-5">
        <button class="btn btn-radius bg-info ml-10 text-white mb-10 mt-5 box-shadow" type="text"
          @click="drawer = true">打开云库</button>
      </div>

      <div class="col-1 mt-20">
        <span style="font-weight:bold">简介：</span>

      </div>
      <div class="col-6 mt-10">
        <el-input style="border-style:solid;border-width:1px;" type="textarea" placeholder="请输入内容" v-model="slogan"
          maxlength="100" show-word-limit :autosize="{ minRows: 2, maxRows: 4}">
        </el-input>
      </div>
      <div class="col-5 mt-15">
        <!-- <el-tooltip content="置顶状态将会自动发布" placement="top" effect="light">
          <el-switch class="mt-10" v-model="top" active-text="置顶" active-color="#ff4949" inactive-text="经典">
          </el-switch>
        </el-tooltip> -->
        
        <button class="btn btn-radius bg-info text-white mb-10 box-shadow" style="float:right;"
          @click="save('RELEASE')">发布</button>
        <button class="btn btn-radius bg-danger text-white mb-10 mr-30 box-shadow" style="float:right;"
          @click="save('DRAFT')">保存草稿</button>
          <button class="btn btn-radius bg-info text-white mb-10 box-shadow mr-30" style="float:right;"
          @click="openRec">打开推荐</button>
          <!-- <button class="btn btn-radius bg-info text-white mb-10 box-shadow mr-30" style="float:right;"
          @click="isOpenSources()">>__</button> -->
      </div>
      <div  class="col-12 mt-10 mb-10" style="height:800px;">
        <button v-show="false" id="link" @click="getLinks()"></button>
        <ky-edit v-if="editContent" :content="editContent"></ky-edit>

        <!-- <editor v-if="show" id="tinymce" v-model="editContent" :init="init"></editor> -->
      </div>
      
      <div class="col-6">
        <span class="ml-10" style="font-weight:bold">标签:</span>
        <el-select v-model="tagValue" value-key="value" multiple filterable allow-create default-first-option
          placeholder="请选择文章标签">
          <el-option v-for="item in tagOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>

        <button class="btn mt-5 ml-10 btn-radius bg-info text-white mb-10 box-shadow" @click="tagW = true">标签管理</button>
        <button class="btn mt-5 ml-10 btn-radius bg-info text-white mb-10 box-shadow"
          @click="preContext()">清空所有</button>

        <div
          :class="like&&isLike?'single-more-articles border-radius-5 single-more-articles--visible':'single-more-articles border-radius-5'">
          <div class="widget-header-2 position-relative mb-30">
            <h5 class="mt-5 mb-30">
              猜你喜欢：这张图片当作背景怎么样呢？
              &nbsp;
              <el-link :disabled="rec.length == 0" icon="el-icon-refresh" @click="recommend()">
              </el-link>
            </h5>
            <button class="single-more-articles-close" @click="isLike = false"><i
                class="elegant-icon icon_close"></i></button>
          </div>
          <div v-loading="isSearch">
            <span v-if="rec.length == 0">没有找到合适的图片</span>
            <el-tooltip class="item" effect="dark" content="点击设置为文章背景" placement="top">
              <img @click="setUrl()" v-if="rec.length>0" :src="rec[current].urls.small_s3" style="hight:200px;"
                class="border-radius-5">
            </el-tooltip>
            <el-button class="mt-10" @click="nextPic(-1)" icon="el-icon-arrow-left">上一个</el-button>
            <el-button class="mt-10" @click="nextPic(1)">下一个<i class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </div>
        </div>

      </div>

    </div>
  </div>
</template>

<script>
import kyEdit from './ky-edit';


  // 代码高亮
  import hljs from 'highlight.js'
  import 'highlight.js/styles/monokai-sublime.css'


  // import "../../utils/media" // 不显示占位图片的视频插件
  import KyArticle from '@/components/module/ky-article'
  import Resources from '@/components/module/resources'
  import Tag from '@/components/module/tags'
  import bus from '../../utils/bus.js'
  import codeFormat from './js/htmlFormat.js'


  let that;
  let Base64 = require('js-base64').Base64
  export default {
    components: {
      kyEdit,
      KyArticle,
      Resources,
      Tag,
    },
    props: {
      docid: {
        type: Number,
        default: 0
      },
      show: {
        type: Boolean,
        default: true
      },
    },
    //监听属性 类似于data概念
    computed: {},
    beforeCreate() {},
    data() {
      return {
        widthSource:12,
        sourceOpen:false,
        cmOptions: {
        theme: !this.cmTheme || this.cmTheme === "default" ? "default" : this.cmTheme,  // 主题
        mode: !this.cmMode || this.cmMode === "default" ? "htmlmixed" : this.cmMode,  // 代码格式
        tabSize: 4,  // tab的空格个数
        indentUnit: !this.cmIndentUnit ? 2 : this.cmIndentUnit,  // 一个块（编辑语言中的含义）应缩进多少个空格
        autocorrect: true,  // 自动更正
        spellcheck: true,  // 拼写检查
        lint: true,  // 检查格式
        lineNumbers: true,  //是否显示行数
        lineWrapping: true, //是否自动换行
        styleActiveLine: true,  //line选择是是否高亮
        keyMap: 'sublime',  // sublime编辑器效果
        matchBrackets: true,  //括号匹配
        autoCloseBrackets: true,  // 在键入时将自动关闭括号和引号
        matchTags: { bothTags: true },  // 将突出显示光标周围的标签
        foldGutter: true,  // 可将对象折叠，与下面的gutters一起使用
        gutters: [
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter"
        ],
        highlightSelectionMatches: {
          minChars: 2,
          style: "matchhighlight",
          showToken: true
        },
      },
      enableAutoFormatJson: this.autoFormatJson == null ? true : this.autoFormatJson,  // json编辑模式下，输入框失去焦点时是否自动格式化，true 开启， false 关闭
  
        downloadUrl: 'http://dev.kingyin.club:9000/cloud/',
        isSearch: false,
        current: 0,
        like: false,
        isLike: true,
        rec: [],
        isOp: false,
        drawer: false,
        tagW: false,
        preLook: false,
        imgSwitch: false,
        background: '',
        title: '',
        slogan: '',
        tagNum: '',
        nickname: '猪皮恶霸',
        tagOptions: ['CSS', "HTML", "JS"],
        tagValue: [],
        tagIds: [],
        top: 0,
        editContent: '',
        
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      
      linkT:'',
      linkA:'',
      isLinkSearch:false,
      isLink:false,
      linkRec:{
        txt:'',
        rec:[],
        current:1,
        size:2,
        total:0
      }
      }
    },
    methods: {
      
      overflowHidForText(val, max = 42) {
        let textLength = val.length;
        let resultText = '';
        if (textLength > max) {
          resultText = val.slice(0, max) + '...'
        } else {
          resultText = val
        }
        return resultText
      },
      isOpenSources() {
        if (this.sourceOpen) {
          this.sourceOpen = false;
          this.$forceUpdate();
        } else {
          this.editContent = this.format(this.editContent);
          this.sourceOpen = true;
          this.$forceUpdate();
        }
      },
      resetLint() {
      if (!this.$refs.myCm.codemirror.getValue()) {
        this.$nextTick(() => {
          this.$refs.myCm.codemirror.setOption("lint", false);
        });
        return;
      }
      this.$refs.myCm.codemirror.setOption("lint", false);
      this.$nextTick(() => {
        this.$refs.myCm.codemirror.setOption("lint", true);
      });
    },
    
    onCmCodeChanges(cm, changes) {
      this.editContent = cm.getValue();
      this.resetLint();
    },
    
      format(data) {
        // var max = codeFormat.format(data);
        // var min = codeFormat.yasuo(max);
        // console.log(max);
        // console.log(min);
        return data;
      },
      
      openRec() {
        if (this.title.length < 10) {
          Notiflix.Notify.Info('标题写的合理会自动推荐封面哦！');
        } else {
          this.isLike = true;
          this.like = true;
        }
      },
      setUrl() {
        this.background = this.rec[this.current].urls.regular;
        Notiflix.Notify.Info('已选择推荐背景');
        this.like = false;
      },
      nextPic(i) {
        if (i > 0 && this.current == this.rec.length - 1) {
          this.current = 0;
        } else if (i < 0 && this.current == 0) {
          this.current = this.rec.length - 1;
        } else {
          this.current = this.current + i;
        }
      },
      recommend() {
        this.searchPic();
      },
      async searchPic() {
        this.isSearch = true;
        const pram = {
          query: this.title
        }
        var res = await this.$api.search.searchPhoto(pram);
        if (res.code == 20000) {
          this.rec = res.data.results;
          this.like = true;
        }
        this.isSearch = false;
      },
      async getDoc() {
        if (this.docid == 0) {
          this.editContent = '<p></P>'
          return 0;
        }
        this.isOp = true;
        const pram = {
          id: this.docid
        }
        var res = await this.$api.core.getEditDocument(pram);
        if (res.code == 20000) {
          this.title = res.data.title;
          this.background = res.data.background;
          this.slogan = res.data.slogan;
          this.editContent = this.format(Base64.decode(res.data.context));
          if (res.data.status == 'TOP') {
            this.top = true;
          }
          this.tagNum = res.data.tag;
          this.tagValue = [];
          for (const t of res.data.tag.split('-')) {
            if (t != '') {
              this.tagValue.push(t);
            }
          }
        }
        this.isOp = false;
      },
      intersection(a, b) {
        const s = new Set(b);
        return [...new Set(a)].filter(x => s.has(x));
      },
      async getTag() {
        this.isOp = true;
        var res = await this.$api.core.getTags();
        this.tagOptions = res.data
        var ids = [];
        for (const i of this.tagOptions) {
          ids.push(i.id);
        }
        // 交集
        let resdata = JSON.parse(JSON.stringify(this.tagValue)).map(Number);
        if (resdata.length != 0) {
          this.tagValue = this.intersection(ids, resdata);
        }
        this.isOp = false;
      },
      createTags() {
        let tags = '';
        for (const t of this.tagValue) {
          if (t == undefined) {
            continue;
          }
          console.log(t);
          tags = tags+t + '-';
        }
        return tags;
      },
      async save(status) {
        let tags = this.createTags();
        
        if (this.$commons.isEmptyString(this.title) || this.title.length < 10) {
          Notiflix.Report.Info('提示', '标题部分不少于10个字，以便继续流程', '好的')
          return
        }
        if (this.$commons.isEmptyString(this.background)) {
          Notiflix.Report.Info('提示', '请填写完整背景部分，以便继续流程', '好的')
          return
        }
        if (this.$commons.isEmptyString(this.slogan) || this.slogan.length < 20) {
          Notiflix.Report.Info('提示', '简介部分不少于20字', '好的')
          return
        }
        if (this.$commons.isEmptyString(this.editContent)) {
          Notiflix.Report.Info('提示', '请填写完整正文部分，以便继续流程', '好的')
          return
        }
        this.isOp = true;
        const pram = {
          id: this.docid,
          title: this.title,
          slogan: this.slogan,
          status: this.top ? 'TOP' : status,
          context: Base64.encode(this.editContent),
          tag: tags,
          background: this.background
        }
        var res = await this.$api.core.save(pram);
        this.isOp = false;
      },
      tagClose(done) {
        // 刷新标签
        this.getTag()
        done();
      },
      preContext() {
        this.$parent.docId = 0;
        this.docid = 0;
        this.title = '';
        this.slogan = '';
        this.tagValue = [];
        this.background = '';
        this.top = false;
        this.editContent = '<p></p>';
        const pram = {
          name: 'edit',
          data: this.editContent
        }
        bus.$emit('clear', pram);
      
        // tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('img'), 'border-radius-5');
        // this.preLook = true;
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      showMain() {
        // 监听事件
        bus.$on('update', res => {
          if (res.name == 'content') {
            this.editContent = res.data;
          }

        })
      },
    },
    created() {
      try {
      if (!this.editContent) {
        this.cmOptions.lint = false;
        return;
      }
      if (this.cmOptions.mode === "application/json") {
        if (!this.enableAutoFormatJson) {
          return;
        }
        this.editContent = this.format(this.editContent);
      }
    } catch (e) {
    }
    },
    
    mounted() {
      this.showMain();
      this.getDoc();
      	setTimeout(() => {
        this.getTag();
     }, 500);

      
    },
    watch: {
      editContent(n,o) {
        this.$forceUpdate();
      },
      title(n, o) {
        if (n.length > 9 && this.$commons.isEmptyString(this.background) && this.rec.length == 0) {
          this.searchPic();
          Notiflix.Notify.Info(this.rec[0].alt_description);
        }

      },
      show(val) {
        if (val) {
          this.editContent = ''
        }
      }
    },

  }

</script>
<style lang="scss">
.noy::-webkit-scrollbar {
    display: none;
  }
#sources{
  .CodeMirror {
      overscroll-y: scroll !important;
      // height: auto !important;
      height: 680px;
    }
}
  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
.editor {
    // width: 700px;
    line-height: normal !important;
     .ql-editor {
      min-height: 750px !important;
      height: 750px;;
    }
    .ql-snow .ql-tooltip[data-mode='link']::before {
      content: '请输入链接地址:';
    }
    .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
      border-right: 0px;
      content: '保存';
      padding-right: 0px;
    }

    .ql-snow .ql-tooltip[data-mode='video']::before {
      content: '请输入视频地址:';
    }

    .ql-snow .ql-picker.ql-size .ql-picker-label::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item::before {
      content: '14px';
    }
    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='small']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='small']::before {
      content: '10px';
    }
    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='large']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='large']::before {
      content: '18px';
    }
    .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='huge']::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='huge']::before {
      content: '32px';
    }

    .ql-snow .ql-picker.ql-header .ql-picker-label::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item::before {
      content: '文本';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
      content: '标题1';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
      content: '标题2';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
      content: '标题3';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
      content: '标题4';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
      content: '标题5';
    }
    .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
    .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
      content: '标题6';
    }

    .ql-snow .ql-picker.ql-font .ql-picker-label::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item::before {
      content: '标准字体';
    }
    .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
      content: '衬线字体';
    }
    .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
      content: '等宽字体';
    }
    
  }
</style>
